package com.lgcns.android2;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;

public class Util {

    /**
     * profile 이미지를 /data/data/package_name/files/사번.jpg 혹은 DB에서 가져와 Bitmap으로 리턴
     * 
     * /data 영역의 이미지가 우선이며 없는 경우 DB의 BLOB 형태 이미지를 가져온다.
     * 
     * @param context
     * @param idNum 사번
     * @return
     */
    public static Bitmap getProfileImage(Context context, int idNum) {
        Uri uri = Uri.withAppendedPath(ProfileProvider.PROFILES_CONTENT_URI, String.valueOf(idNum));
        Cursor cursor = ((Activity)context).managedQuery(uri, ProfileProvider.PROJECTION_PHOTO, null, null, null);
        cursor.moveToFirst();

        return getProfileImage(context, cursor, new BitmapFactory.Options());
    }

    public static Bitmap getProfileImage(Context context, Cursor cursor, BitmapFactory.Options options) {
        Bitmap bm = null;
        int idNum = cursor.getInt(cursor.getColumnIndex(Constants.ID_NUM));
        File takenPhoto = context.getFileStreamPath(idNum + ".jpg");

        if (takenPhoto.exists()) {
            bm = BitmapFactory.decodeFile(takenPhoto.getAbsolutePath(), options);
        } else {
            byte[] bb = cursor.getBlob(cursor.getColumnIndex(Constants.PHOTO));
            bm = BitmapFactory.decodeByteArray(bb, 0, bb.length, options);
        }
        
        return bm;
    }
    
    public static void closeSilently(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException e) {
                ;
            }
        }
    }

}
